const express = require('express');//引入express模块
const app = express();
const db = require('./data-source');

//设置参数解析工具
app.use(express.json());// for parsing application/json
app.use(express.urlencoded({extended: true}));// for parsing application/x-www-form-urlencoded

//设置允许跨域访问该服务.
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    //Access-Control-Allow-Headers ,可根据浏览器的F12查看,把对应的粘贴在这里就行
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Methods', '*');
    res.header('Content-Type', 'application/json;charset=utf-8');
    next();
});



app.get("/api/private/v1/get", function (req, res) {
    let queryString = "select * from t_user where id=$'" + req.query.id + "'";
    console.log("queryString:" + queryString);
    db.connection.query(queryString, function (err, result) {
        if (err) {
            res.send({
                code: 200,
                success: true,
                msg: "查询异常:" + err.message,
                data: {}
            })
        }
        if (result.length !== 0) {
            res.send({
                code: 200,
                success: true,
                msg: "查询成功",
                data: result[0]
            })
        } else {
            res.send({
                code: 1001,
                success: true,
                msg: "未查到信息",
                data: {}
            })
        }
    });
})

//定义登录请求
app.post('/api/private/v1/login', function (req, res) {
    console.log(req.body);
    let queryString =
        "select * from t_user where username='" + req.body.username + "' and password='" + req.body.password + "'";
    db.connection.query(queryString, function (err, result) {
        if (err) throw err;
        console.log("result:", result);
        if (result.length !== 0) {
            res.send({
                code: 200,
                success: true,
                msg: "登录成功"
            })
        } else {
            res.send({
                code: 1001,
                success: true,
                msg: "登录失败"
            })
        }
    });
});

//定义端口，此处所用为3000端口，可自行更改
const server = app.listen(3000, function () {
    console.log('running 3000...');
});
